<template>
    <view :data-theme="globPrimary">
        <u-navbar>
            <exam-count-down
                ref="examCountDown"
                :timestamp="timestamp"
                :pattern="pattern"
                :autoplay="false"
                :custom-style="{
                    fontSize: '32rpx',
                    color: '#303133',
                }"
                @change="handleTimestampChange"
                @end="handleTimestampEnd"
            ></exam-count-down>
            <view class="u-flex topic-navbar-right">
                <view class="topic-navbar-collection" @click="changeCollection">
                    <u-icon
                        name="star-fill"
                        :color="collected ? '#FF8A52' : '#DCDFE6'"
                        size="40"
                    ></u-icon>
                </view>
                <view class="topic-navbar-sheet" @click="$u.debounce(onOpenCard, 200)">
                    <u-image
                        width="40"
                        height="40"
                        src="@/pageFound/static/images/exam_sheet_icon.png"
                    ></u-image>
                </view>
                <view class="topic-navbar-btn">
                    <edu-button
                        type="primary"
                        size="mini"
                        @click="handleTopicConfirm"
                        :disabled="disabled"
                        >交卷</edu-button
                    >
                </view>
            </view>
        </u-navbar>
        <view class="topic-header u-flex u-line-1">
            <view class="title u-line-1">{{ examTitle }}</view>
            <u-image
                width="28rpx"
                height="32rpx"
                src="@/pageFound/static/images/maker.png"
                class="img"
            ></u-image>
            <view class="conut active">{{ examIndex + 1 }}</view>
            <view class="conut">/{{ examCount }}</view>
        </view>

        <view class="topic-body" v-for="item in topicList" :key="item.id">
            <exam-question
                :question="item"
                :question-id="item.id"
                :question-type="item.question_type"
                :value="questionValue(item)"
                :score-item="topicScoreItem"
                @change="handleQuestionChange"
            ></exam-question>
        </view>

        <exam-pagination
            :show-prev-button="examIndex > 0"
            :show-next-button="examIndex < examCount - 1"
            @prev="handleTopicPrev"
            @next="handleTopicNext"
        ></exam-pagination>

        <!-- 答题卡 -->
        <exam-card
            ref="examCard"
            v-model="cardVisible"
            :title="examTitle"
            :timestamp="timestamp"
            :pattern="pattern"
            :disabled="disabled"
            @change="handleTopicChange"
            @confirm="handleTopicConfirm"
        ></exam-card>

        <u-modal
            show-cancel-button
            v-model="modelVisible"
            :show-title="false"
            @confirm="onSubmitPaper"
            content="确认提交试卷吗？"
            :confirm-style="{ 'border-left': '1px solid #e4e7ed' }"
            :confirm-color="globPrimaryColor"
        >
        </u-modal>

        <u-toast ref="uToast" />
    </view>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import examQuestion from '../components/exam-question.vue'
import examPagination from '../components/exam-pagination.vue'
import examCard from '../components/exam-card.vue'
import examCountDown from '../components/exam-count-down.vue'
export default {
    components: {
        examQuestion,
        examPagination,
        examCard,
        examCountDown,
    },
    data() {
        return {
            rollupId: 0,
            paperId: 0,
            loading: false,
            pattern: false, // 时长规则
            timestamp: 0, // 时长
            examTitle: '', // 考试标题
            examCount: 0, // 试题总数
            examWhen: 0, // 考试用时
            topicList: [],
            cardVisible: false,
            modelVisible: false,
            uniqueCode: '',
            disabled: false,

            cutScreenNumber: 0, // 切屏次数
            cutScreenVerify: 0, // 切屏验证次数
        }
    },
    computed: {
        ...mapState({
            examIndex: (state) => state.examination.examIndex,
            examList: (state) => state.examination.examList,
            examAnswerList: (state) => state.examination.examAnswerList,
            examRulesList: (state) => state.examination.examRulesList,
        }),
        ...mapGetters({
            globPrimary: 'designSetting/getGlobTheme',
            globPrimaryColor: 'designSetting/getGlobThemeColor',
            topicId: 'examination/getTopicId',
        }),
        // 收藏状态
        collected() {
            const topic = this.topicList.find((item, index) => item.id == this.topicId)
            if (this.$u.test.empty(topic)) return 0
            return topic.collected
        },
        // 试题的分数
        topicScoreItem() {
            let item = this.examList.find((topic) => topic.topic_id == this.topicId)
            if (item) {
                return item
            }
            return {}
        },
        // 部分id
        partsId() {
            let id = 0
            this.examRulesList.forEach((question) => {
                question.value.forEach((item) => {
                    if (item.topic_id == this.topicId) {
                        id = question.id
                    }
                })
            })
            return id
        },
    },
    onLoad(option) {
        this.rollupId = option.id
        this.paperId = option.paper_id
        this.getRollupInfo()
    },
    onShow() {
        this.onPageVisibility()
    },
    onHide() {
        // 记录退出到后台次数
        this.cutScreenNumber++
    },
    methods: {
        // 获取的基础信息
        getRollupInfo() {
            this.loading = true
            this.$edu.api
                .getRollupBase({
                    rollup_id: this.rollupId,
                    paper_id: this.paperId,
                })
                .then((res) => {
                    const { data } = res
                    this.examTitle = data.title
                    this.examCount = data.total_count
                    this.uniqueCode = data.unique_code
                    this.cutScreenVerify = data.screen_cut //切屏次数
                    this.$store.commit('examination/init', data.parts)
                    this.getExamTopic()
                    // 考试时长
                    if (data.total_time > 0) {
                        this.pattern = true
                        this.timestamp = data.total_time * 60
                    }
                    this.handleTimestampStart()
                })
        },
        // 获取试题
        getExamTopic() {
            uni.showLoading({
                title: '加载中...',
            })
            this.loading = true
            return new Promise((resolve) => {
                this.$edu.api
                    .getRollupTopic({
                        topic_id: this.topicId,
                        paper_id: this.paperId,
                    })
                    .then((res) => {
                        const { data } = res
                        this.topicList = data
                        setTimeout(() => {
                            this.loading = false
                            uni.hideLoading()
                        }, 500)
                        resolve()
                    })
                    .catch((err) => {
                        uni.hideLoading()
                    })
            })
        },
        // 当前值
        questionValue(item) {
            let list = this.examAnswerList.reduce((pre, cur) => pre.concat(cur.data), [])
            const rules = list.find((item) => item.topic_id == this.topicId)
            let empty = null
            if (this.$edu.test.inArray(item.question_type, [1, 2, 8])) {
                empty = ''
            } else if (this.$edu.test.inArray(item.question_type, [3, 4, 5, 7])) {
                empty = []
            }
            if (this.$u.test.empty(rules) || this.$u.test.empty(rules.answer)) {
                return empty
            } else {
                return rules.answer
            }
        },
        // 上一题
        handleTopicPrev() {
            if (!this.loading) {
                this.$store.commit('examination/prev')
                this.getExamTopic()
            }
        },
        // 下一题
        handleTopicNext() {
            if (!this.loading) {
                this.$store.commit('examination/next')
                this.getExamTopic()
            }
        },
        // 当前题
        handleTopicChange(index) {
            if (!this.loading) {
                this.cardVisible = false
                this.$store.commit('examination/change', index)
                this.getExamTopic()
            }
        },
        // 选择的答案变化时
        handleQuestionChange(e) {
            this.$store.commit('examination/changeCurrentAnswer', {
                pid: e.pid,
                id: e.id,
                answer: e.answer,
                topic_level: e.topic_level,
                question_type: e.question_type,
                part_id: this.partsId,
            })
        },
        // 打开答题卡
        onOpenCard() {
            this.cardVisible = true
        },
        // 开始计时
        handleTimestampStart() {
            this.$refs.examCountDown.start()
        },
        // 暂停计时
        handleTimestampPause() {
            this.$refs.examCountDown.pause()
        },
        // 时间改变时
        handleTimestampChange(time) {
            this.timestamp = time
            this.examWhen++
        },
        // 时间结束/交卷
        handleTimestampEnd() {
            this.onSubmitPaper()
        },
        // 交卷
        handleTopicConfirm() {
            this.modelVisible = true
        },
        // 处理提交试卷
        onSubmitPaper() {
            this.disabled = true
            this.handleTimestampPause() // 暂停计时
            uni.showLoading()
            let list = this.examAnswerList
            // 处理答案的数据
            let empty = list.every((item) => this.$u.test.empty(item.data))
            if (empty) {
                list = []
            } else {
                list.forEach((question, j) => {
                    question.data.forEach((item, index) => {
                        if (this.$u.test.empty(item.answer)) {
                            question.data.splice(index, 1)
                        } else {
                            if (this.$edu.test.inArray(item.question_type, [1, 2, 8])) {
                                item.answer = [item.answer]
                            }
                        }
                    })
                })

                list.forEach((question, j) => {
                    if (this.$u.test.empty(question.data)) {
                        list.splice(j, 1)
                    }
                })
            }

            setTimeout(() => {
                this.$edu.api
                    .rdferRollupAnswer({
                        rollup_id: parseInt(this.rollupId),
                        paper_id: parseInt(this.paperId),
                        answer_data: JSON.stringify(list),
                        unique_code: this.uniqueCode,
                        time_takes: this.examWhen,
                    })
                    .then((res) => {
                        this.$u.toast(res.msg)
                        setTimeout(() => {
                            uni.hideLoading()
                            this.$u.route({
                                type: 'back',
                            })
                            this.disabled = false
                        }, 300)
                    })
                    .catch((err) => {
                        uni.hideLoading()
                        this.$u.route({
                            type: 'back',
                        })
                        this.disabled = false
                    })
            }, 1000)
        },
        // 收藏
        changeCollection() {
            if (!this.loading) {
                let status = this.collected == 1 ? 0 : 1
                this.$edu.api
                    .getTopicCollect({
                        topic_id: this.topicId.toString(),
                        status: status,
                    })
                    .then((res) => {
                        this.$u.toast(res.data)
                        let topic = this.topicList.find((item) => item.id == this.topicId)
                        topic.collected = status
                    })
            }
        },
        // 处理切屏
        onPageVisibility() {
            if (this.cutScreenVerify == 0) return
            // 切换次数大于验证次数时自动提交试卷
            if (this.cutScreenNumber > this.cutScreenVerify) {
                this.$refs.uToast.show({
                    title: `你已经切换离开考试页面超过${this.cutScreenVerify}次系统将自动提交答卷！`,
                    type: 'warning',
                })
                setTimeout(() => {
                    // 提交答案
                    this.onSubmitPaper()
                }, 2500)
            }
            // 切换次数等于验证次数时提示用户
            if (this.cutScreenNumber == this.cutScreenVerify) {
                this.$refs.uToast.show({
                    title: `你已经切换离开考试页面${this.cutScreenNumber}次，如果超过${this.cutScreenVerify}次系统会自动提交答卷，请认真作答！`,
                    type: 'warning',
                })
            }
        },
    },
    destroyed() {
        this.$store.commit('examination/init')
    },
}
</script>
<style lang="scss">
page {
    background-color: #ffffff;
}
</style>
<style lang="scss" scoped>
.topic-navbar-right {
    margin-left: auto;
}
.topic-navbar-collection {
    padding: 10px 20rpx;
}
.topic-navbar-sheet {
    padding: 10rpx 20rpx;
    margin-right: 30rpx;
}
.topic-navbar-btn {
    margin-right: 30rpx;
}
.topic-header {
    padding: 30rpx;
    position: relative;
    .title {
        max-width: 60%;
        font-size: 32rpx;
        font-weight: 500;
        color: #303133;
    }
    .img {
        margin-left: auto;
        margin-right: 20rpx;
    }
    .count {
        font-size: 26rpx;
        color: #909399;
    }
    .active {
        @include text-color();
    }
    .answered {
        position: absolute;
        right: 8rpx;
        top: 16rpx;
        z-index: 99;
    }
}
.topic-body {
    padding: 0 30rpx;
    margin-bottom: 30rpx;
}
</style>
